package org.sun.sunshine.io.nio.channel;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

@Slf4j
public class NioSocketChannelClientDemo {
    private static Charset charset = Charset.forName("UTF-8");
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 8080;
    private static final String SRC_PATH = "/Users/yushengjun/IdeaProjects/sunshine/producer/src/main/java/org/sun/sunshine/io/nio/channel/file.txt";

    public static void main(String[] args) {
        sendFile();
    }

    public static void sendFile(){
        Path path = Paths.get(SRC_PATH);
        if (!Files.exists(path))
            throw new RuntimeException("src file not exists");

        try(FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ);
            SocketChannel socketChannel= SocketChannel.open();
        ){
            socketChannel.configureBlocking(false);
            socketChannel.connect(new InetSocketAddress(HOST,PORT));
            //没完成链接，一直等着
            while(!socketChannel.finishConnect()){
                //nothing
            }
            //链接完成开始传输数据
            //传输文件名
            ByteBuffer fileName=charset.encode("file.txt");
            socketChannel.write(fileName);

            //传输文件大小 in bytes
            ByteBuffer fileSize=ByteBuffer.allocate(Long.SIZE);
            Long fileLength  =new File(SRC_PATH).length();
            fileSize.putLong(fileLength);
            fileSize.flip();
            socketChannel.write(fileSize);

            ByteBuffer buffer = ByteBuffer.allocate(1024);
            //传输文件
            int length = 0;
            long progress = 0;
            while ((length = fileChannel.read(buffer)) > 0) {
                buffer.flip();
                socketChannel.write(buffer);
                buffer.clear();
                progress += length;
                //显示百分比
                log.info("| "+(100 * progress / fileLength) + "% |");
            }

            if(length==-1){
                socketChannel.shutdownOutput();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
